/*
 * Copyright (C) 2012 SeekDeepWithin.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package com.seekdeepwithin.DataAccess;

import java.io.*;
import javafx.beans.property.*;
import javafx.concurrent.*;
import org.apache.commons.net.*;
import org.apache.commons.net.ftp.*;

/**
 * User: Jonathan Montiverdi
 * Date: Oct 11, 2012
 *
 * Ftp service returns true if file was downloaded successfully, otherwise false.
 */
public class FtpService extends Service <Boolean>
{
    private StringProperty localFile = new SimpleStringProperty ();
    private StringProperty remoteFile = new SimpleStringProperty ();

    /**
     * Sets the local file to download.
     * @param file The path of the local file to download.
     */
    public final void setLocalFile (String file)
    {
        this.localFile.set (file);
    }

    /**
     * Gets the remote file to download.
     * @return The path of the remote file to download.
     */
    public final String getLocalFile ()
    {
        return this.localFile.get ();
    }

    /**
     * Gets the search text property.
     * @return Search text property.
     */
    public final StringProperty localFileProperty ()
    {
        return this.localFile;
    }

    /**
     * Sets the remote file to download.
     * @param file The path of the remote file to download.
     */
    public final void setRemoteFile (String file)
    {
        this.remoteFile.set (file);
    }

    /**
     * Gets the remote file to download.
     * @return The path of the remote file to download.
     */
    public final String getRemoteFile ()
    {
        return this.remoteFile.get ();
    }

    /**
     * Gets the search text property.
     * @return Search text property.
     */
    public final StringProperty remoteFileProperty ()
    {
        return this.remoteFile;
    }

    /**
     * Creates the task that performs the action.
     * @return Newly created task.
     */
    @Override
    protected Task<Boolean> createTask ()
    {
        final String m_LocalFile = getLocalFile ();
        final String m_RemoteFile = getRemoteFile ();
        return new Task<Boolean> () {
            @Override protected Boolean call ()
            {
                FTPClient ftp = null;
                try
                {
                    boolean downloaded = false;
                    String tempFile = localFile + "_temp";
                    if (!DeleteFile (tempFile)) return false;
                    ftp = new FTPClient ();
                    ftp.addProtocolCommandListener(new PrintCommandListener(
                                                   new PrintWriter(System.out)));
                    ftp.connect ("seekdeepwithin.com");
                    if (ftp.isConnected ())
                    {
                        ftp.login ("jonathan@seekdeepwithin.com", "jonathan");
                        ftp.setFileType(FTP.BINARY_FILE_TYPE);
                        ftp.enterLocalPassiveMode();
                        try (OutputStream outputStream = new FileOutputStream (tempFile))
                        {
                            ftp.retrieveFile (m_RemoteFile, outputStream);
                            downloaded = true;
                        }
                        ftp.logout ();
                    }

                    if (downloaded)
                    {
                        File f = new File (tempFile);
                        if (!DeleteFile (m_LocalFile)) return false;
                        f.renameTo (new File (m_LocalFile));
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    ex.printStackTrace (System.err);
                }
                finally
                {
                    try
                    {
                        if (ftp != null && ftp.isConnected ())
                            ftp.disconnect ();
                    }
                    catch (IOException ex)
                    {
                        ex.printStackTrace (System.err);
                    }
                }
                return false;
            }
        };
    }

    /**
     * Deletes the give file.
     *
     * @param localFile File to delete.
     * @return True if successful, otherwise false.
     */
    private static boolean DeleteFile (String localFile)
    {
        // Delete the current file if it exits...
        File f = new File (localFile);
        if (f.isFile ())
        {
            if (!f.delete ())
            {
                return false;
            }
        }
        return true;
    }

}
